#!/usr/bin/env python3
"""
Flask博客系统测试脚本
用于验证应用基本功能是否正常
"""

import os
import sys
import tempfile
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_imports():
    """测试模块导入"""
    print("🔍 测试模块导入...")
    try:
        from app import create_app, db
        from app.models import User, Post, Category, Tag, Comment
        from app.forms import LoginForm, PostForm, CommentForm
        print("✅ 所有模块导入成功")
        return True
    except ImportError as e:
        print(f"❌ 模块导入失败: {e}")
        return False

def test_app_creation():
    """测试应用创建"""
    print("🔍 测试应用创建...")
    try:
        from app import create_app
        app = create_app('testing')
        with app.app_context():
            print("✅ 应用创建成功")
        return True
    except Exception as e:
        print(f"❌ 应用创建失败: {e}")
        return False

def test_database_creation():
    """测试数据库创建"""
    print("🔍 测试数据库创建...")
    try:
        from app import create_app, db
        from app.models import User, Post, Category, Tag, Comment
        
        app = create_app('testing')
        with app.app_context():
            db.create_all()
            
            # 测试创建用户
            user = User(username='testuser', email='test@example.com')
            user.set_password('testpass')
            db.session.add(user)
            db.session.commit()
            
            # 测试创建分类
            category = Category(name='测试分类', slug='test-category')
            db.session.add(category)
            db.session.commit()
            
            # 测试创建标签
            tag = Tag(name='测试标签', slug='test-tag')
            db.session.add(tag)
            db.session.commit()
            
            # 测试创建文章
            post = Post(
                title='测试文章',
                slug='test-post',
                content='这是一篇测试文章',
                content_html='<p>这是一篇测试文章</p>',
                author_id=user.id,
                category_id=category.id,
                is_published=True
            )
            db.session.add(post)
            post.tags.append(tag)
            db.session.commit()
            
            # 测试创建评论
            comment = Comment(
                content='这是一条测试评论',
                post_id=post.id,
                guest_name='测试用户',
                guest_email='comment@example.com',
                is_approved=True
            )
            db.session.add(comment)
            db.session.commit()
            
            print("✅ 数据库操作成功")
        return True
    except Exception as e:
        print(f"❌ 数据库操作失败: {e}")
        return False

def test_routes():
    """测试路由"""
    print("🔍 测试路由...")
    try:
        from app import create_app
        
        app = create_app('testing')
        with app.test_client() as client:
            # 测试首页
            response = client.get('/')
            assert response.status_code == 200
            print("✅ 首页路由正常")
            
            # 测试登录页面
            response = client.get('/auth/login')
            assert response.status_code == 200
            print("✅ 登录页面路由正常")
            
            # 测试管理后台（应该重定向到登录）
            response = client.get('/admin/')
            assert response.status_code in [200, 302]
            print("✅ 管理后台路由正常")
            
        return True
    except Exception as e:
        print(f"❌ 路由测试失败: {e}")
        return False

def test_forms():
    """测试表单"""
    print("🔍 测试表单...")
    try:
        from app.forms import LoginForm, PostForm, CommentForm
        
        # 测试登录表单
        login_form = LoginForm(data={
            'username': 'testuser',
            'password': 'testpass',
            'remember_me': False
        })
        assert login_form.validate()
        print("✅ 登录表单正常")
        
        # 测试评论表单
        comment_form = CommentForm(data={
            'name': '测试用户',
            'email': 'test@example.com',
            'content': '这是一条测试评论'
        })
        assert comment_form.validate()
        print("✅ 评论表单正常")
        
        return True
    except Exception as e:
        print(f"❌ 表单测试失败: {e}")
        return False

def main():
    """主测试函数"""
    print("🧪 Flask博客系统测试")
    print("=" * 50)
    
    tests = [
        test_imports,
        test_app_creation,
        test_database_creation,
        test_routes,
        test_forms
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        try:
            if test():
                passed += 1
            print()
        except Exception as e:
            print(f"❌ 测试异常: {e}")
            print()
    
    print("=" * 50)
    print(f"📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有测试通过! 应用可以正常运行")
        return True
    else:
        print("⚠️  部分测试失败，请检查错误信息")
        return False

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)

